﻿function getp10(caname,p10name,keytypename,keysnname,dn)
{	
	var p10Value = document.getElementById('p10').value;
	if(p10Value==null || p10Value=="")
	{
		var obj;
		var pwd = initPIN();				
		try
		{			
			obj = new ActiveXObject("NetcaBpmsClientCom.PKI");
			if(obj.IsInstalled(caname))
			{						
				obj.SetCA(caname);

				if(obj.KeyCount>1)
				{
					alert("最多只能插入1个key");
					return;
				}
				
				obj.Connect();	
				if(pwd != null)
				{
					obj.VerifyPIN(pwd);
					document.getElementById("userPin").value = pwd;
				}
					
				if(keytypename!="")
				{
					document.getElementById(keytypename).value=obj.Type;
				}
				if(keysnname!="")
				{
					document.getElementById(keysnname).value=obj.SerialNumber;
				}

				document.getElementById(p10name).value=obj.GenerateP10(dn);
			}
			else
			{
				alert("没有安装该CA的支持的DLL");
			}
		}
		catch (e)
		{
			alert(e.message);
		}
	}
}

function getdn(E,CN,OU,O,L,S,C)
{
//E-CN-OU-O-L-S-C
	var dn="";
	var count=0;
	if(E!="")
	{
		if(count>0)
			dn+=",";
		dn+="E="+E;
		count++;
	}
	if(CN!="")
	{
		if(count>0)
			dn+=",";
		dn+="CN="+CN;
		count++;
	}
	if(OU!="")
	{
		if(count>0)
			dn+=",";
		dn+="OU="+OU;
		count++;
	}
	if(O!="")
	{
		if(count>0)
			dn+=",";
		dn+="O="+O;
		count++;
	}
	if(L!="")
	{
		if(count>0)
			dn+=",";
		dn+="L="+L;
		count++;
	}
	if(S!="")
	{
		if(count>0)
			dn+=",";
		dn+="S="+S;
		count++;
	}
	if(C!="")
	{
		if(count>0)
			dn+=",";
		dn+="C="+C;
		count++;
	}
	
	return dn;
}

// 返回 userPin
function initPIN()
{
	var usbKeyObj;
	var flag = false;
	var soPin = null; // 管理员PIN
	var userPin = "12345678"; // 用户PIN
	var device; 
	var ETAX_SUCCESS = 0;
	var ETAX_MF_EXIST = -3;
	
	try
	{
		// 1. connect
		usbKeyObj=new ActiveXObject("NetcaEtaxCOM.USBKeyObject");
		
		flag = usbKeyObj.UKeyConnect(0);
		if(flag!=ETAX_SUCCESS) 
		{
			alert("连接USBKey失败");
			return null;
		}
	
		// 2. getPin
		soPin = usbKeyObj.USBKeyGetRandomPin();
		if(soPin==null) // 需要测试长度
		{
			alert("获取管理员pin失败");
			usbKeyObj.UKeyDisConnect();
			return null;
		}
		
		// 3. initPin
		flag = usbKeyObj.USBKeyInitEx(userPin, soPin);
		usbKeyObj.UKeyDisConnect();
		if(flag==ETAX_SUCCESS) 
		{
			document.getElementById("soPin").value= soPin;
			return userPin;
		}
		else if(flag == ETAX_MF_EXIST)
		{
			flag = usbKeyObj.USBKeyFormatEx(userPin, soPin, 0);
			if(flag==ETAX_SUCCESS) 
			{
				document.getElementById("soPin").value= soPin;
				return userPin;
			}
			return null;
		}
		return null;
	}
 	catch (e)
	{
		alert(e.message);
		return null;
	}
 
}